package com.yjy.fuyao.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.wxpay.sdk.WXPayUtil;
import com.yjy.fuyao.order.client.StuClient;
import com.yjy.fuyao.order.client.UcenterClient;
import com.yjy.fuyao.order.entity.CourseOrder;
import com.yjy.fuyao.order.mapper.CourseOrderMapper;
import com.yjy.fuyao.order.service.CourseOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjy.fuyao.utils.util.HttpClient;
import com.yjy.fuyao.utils.util.OrderNoUtil;
import com.yjy.fuyao.utils.vo.CourseInfoVo;
import com.yjy.fuyao.utils.vo.UserVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author yjy
 * @since 2022-05-14
 */
@Service
public class CourseOrderServiceImpl extends ServiceImpl<CourseOrderMapper, CourseOrder> implements CourseOrderService {


    @Resource
    private StuClient stuClient;

    @Resource
    private UcenterClient ucenterClient;

    @Resource
    private RedisTemplate redisTemplate;

    //创建订单
    @Override
    public String saveOrder(String courseId, String userId) {
        //远程调用课程服务，根据课程id获取课程信息
        CourseInfoVo courseDto = stuClient.getCourseInfo(courseId);

        //远程调用用户服务，根据用户id获取用户信息
        UserVo user = ucenterClient.getUserInfo(userId);

        //创建订单
        CourseOrder order = new CourseOrder();
        order.setOrderNo(OrderNoUtil.getOrderNo());
        order.setCourseId(courseId);
        order.setCourseTitle(courseDto.getTitle());
        order.setCourseCover(courseDto.getCover());
//        order.setTeacherName("test");
        order.setTotalFee(courseDto.getPrice());
        order.setUserId(userId);
        order.setMail(user.getMail());
        order.setNickname(user.getNickname());
        order.setStatus(0);
        order.setPayType(1);
        baseMapper.insert(order);

        return order.getOrderNo();
    }

    @Override
    public Map<String, Object> orderPageList(Page<CourseOrder> pageParam, String userId) {
        List<CourseOrder> records;
        long current,pages,size,total;
        boolean hasNext,hasPrevious;

        Map<String, Object> map = new HashMap<String, Object>();
        LambdaQueryWrapper<CourseOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseOrder::getUserId,userId);
        baseMapper.selectPage(pageParam,queryWrapper);
        records = pageParam.getRecords();
        current = pageParam.getCurrent();
        pages = pageParam.getPages();
        size = pageParam.getSize();
        total = pageParam.getTotal();
        hasNext = pageParam.hasNext();
        hasPrevious = pageParam.hasPrevious();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    @Override
    public Map createNative(String orderNo) {
        try {
            //根据订单id获取订单信息
            QueryWrapper<CourseOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no",orderNo);
            CourseOrder order = baseMapper.selectOne(wrapper);

            Map pay = new HashMap();
            //1、设置支付参数
            pay.put("appid", "wx74862e0dfcf69954");
            pay.put("mch_id", "1558950191");
            pay.put("nonce_str", WXPayUtil.generateNonceStr());
            pay.put("body", order.getCourseTitle());
            pay.put("out_trade_no", orderNo);
            pay.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            pay.put("spbill_create_ip", "127.0.0.1");
            pay.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            pay.put("trade_type", "NATIVE");

            //2、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(pay, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //4、封装返回结果集

            Map map = new HashMap<>();
            map.put("out_trade_no", orderNo);
            map.put("course_id", order.getCourseId());
            map.put("total_fee", order.getTotalFee());
            map.put("result_code", resultMap.get("result_code"));
            map.put("code_url", resultMap.get("code_url"));

            //微信支付二维码2分钟过期，可采取2分钟未支付取消订单
            redisTemplate.opsForValue().set(orderNo, map, 120, TimeUnit.SECONDS);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }

    @Override
    public void updateOrderStatus(Map<String, String> map) {
        //获取订单id
        String orderNo = map.get("out_trade_no");
        //根据订单id查询订单信息
        QueryWrapper<CourseOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        CourseOrder order = baseMapper.selectOne(wrapper);

        if(order.getStatus().intValue() == 1) return;
        order.setStatus(1);
        baseMapper.updateById(order);
    }


    @Override
    public Map queryPayStatus(String orderNo) {
        Object value = redisTemplate.opsForValue().get(orderNo);
        if(value == null){
            return null;
        }
        try {
            //1、封装参数
            Map m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //6、转成Map
            //7、返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
